package com.bckj.fastboot.upms.biz.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bckj.fastboot.upms.biz.core.perm.Perms;
import com.bckj.fastboot.upms.biz.core.perm.PermsHandler;
import com.bckj.fastboot.upms.biz.repository.SysRoleRepository;
import com.bckj.fastboot.upms.biz.convert.SysRoleConvert;
import com.bckj.fastboot.upms.api.vo.SysRoleVO;
import com.bckj.fastboot.upms.api.dto.SysRoleRequest;
import com.bckj.fastboot.upms.api.dto.SysRoleQuery;
import com.bckj.fastboot.upms.api.entity.SysRole;

import com.bckj.fastboot.core.lang.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 角色表(SysRole)domain-service
 *
 * @author wfc
 * @since 2023-09-14 10:12:51
 */
@Service
@RequiredArgsConstructor
public class SysRoleService {

    private final SysRoleRepository sysRoleRepository;
	
    private final SysRoleConvert sysRoleConvert;

    private final PermsHandler permsHandler;
	
    /**
     * 列表
     *
     * @param query req
     * @return list
     */
    public List<SysRoleVO> list(SysRoleQuery query){
        return sysRoleRepository.getBaseMapper().list(query);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     */
    private void checkRoleNameUnique(SysRole role) {
        SysRole sr = sysRoleRepository.getOne(Wrappers.<SysRole>lambdaQuery()
                .eq(SysRole::getRoleName, role.getRoleName())
                .eq(SysRole::getDeleteFlag, 0));
        if (sr != null && !Objects.equals(sr.getId(), role.getId())) {
            throw new BusinessException("该角色名称已存在");
        }
    }

     /**
     * 保存
     *
     * @param request req
     */
    public boolean save(SysRoleRequest request) {
        SysRole entity = sysRoleConvert.request2Bean(request);
        checkRoleNameUnique(entity);
        return sysRoleRepository.save(entity);
    }

    /**
     * 修改
     *
     * @param request req
     */
    public boolean update(SysRoleRequest request) {
        SysRole entity = sysRoleConvert.request2Bean(request);
        checkRoleNameUnique(entity);
        return sysRoleRepository.updateById(entity);
    }
    
    /**
     * 详情
     *
     * @param id id
     * @return vo
     */
    public SysRoleVO details(Long id) {
        SysRole bean = sysRoleRepository.getById(id);
        if (null == bean) {
            throw new BusinessException("当前对象不存在!");
        }
        return sysRoleConvert.bean2VO(bean);
    }

	/**
	 * 根据Id移除
	 *
	 * @param id id
	 * @return boolean
	 */
	public boolean remove(Long id) {
        //TODO LIMIT
		return sysRoleRepository.removeById(id);
	}

    public boolean savePerms(SysRoleRequest request) {
        Perms perms = new Perms(request.getId(), 0, request.getPermsType());
        permsHandler.trans(perms, request.getDataSelect(), true);
        permsHandler.savePerms(perms);
        return true;
    }
}

